using System;
using System.Collections.Generic;
using System.Web.Http;
using FreshCommonUtility.Cache;
using WeChatCmsCommon.EnumBusiness;
using WeChatModel;
using WeChatModel.DatabaseModel;
using WeChatService;
using System.Linq;
using WeChatNoteCostApi.WeChatInnerModel;

namespace WeChatNoteCostApi.Controllers
{
    /// <summary>
    /// 项目人员管理
    /// </summary>
    public class ProjectManagerController : ApiControllerBase
    {
        #region [1、项目管理]

        /// <summary>
        /// 获取项目列表（包含人员信息）
        /// </summary>
        /// <param name="token">用户token</param>
        /// <returns></returns>
        [HttpGet]
        public ResponseBaseModel<dynamic> GetProjectsWithPersons(string token)
        {
            var resultMode = new ResponseBaseModel<dynamic>
            {
                ResultCode = ResponceCodeEnum.Fail,
                Message = ""
            };

            var userData = RedisCacheHelper.Get<WeChatAccountModel>(RedisCacheKey.AuthTokenKey + token);
            var tempUserId = userData?.AccountId;
            if (tempUserId == null || tempUserId < 1)
            {
                resultMode.Message = "登录失效，请重新登录";
                return resultMode;
            }

            var userId = tempUserId.Value;

            try
            {
                var projectService = new ProjectService();
                var personService = new PersonService();
                var personTagService = new PersonTagService();

                // 获取项目列表
                int count;
                var projects = projectService.GetList(new List<long> { userId }, 1, 1000, out count);
                var result = new List<object>();

                foreach (var project in projects)
                {
                    // 获取项目下的人员
                    var persons = personService.GetListByProjectId(project.Id, userId);
                    var personList = new List<object>();

                    foreach (var person in persons)
                    {
                        // 获取人员标签
                        var tags = personTagService.GetListByPersonId(person.Id, userId);
                        var tagList = tags.Select(t => new { id = t.Id, name = t.TagName }).ToList();

                        personList.Add(new
                        {
                            id = person.Id,
                            name = person.PersonName,
                            color = person.PersonColor,
                            tags = tagList
                        });
                    }

                    result.Add(new
                    {
                        id = project.Id,
                        name = project.ProjectName,
                        startDate = project.StartDate.ToString("yyyy-MM-dd"),
                        persons = personList
                    });
                }

                resultMode.Data = result;
                resultMode.ResultCode = ResponceCodeEnum.Success;
            }
            catch (Exception ex)
            {
                resultMode.Message = "获取数据失败：" + ex.Message;
            }

            return resultMode;
        }

        /// <summary>
        /// 获取无项目的人员列表
        /// </summary>
        /// <param name="token">用户token</param>
        /// <returns></returns>
        [HttpGet]
        public ResponseBaseModel<dynamic> GetUnassignedPersons(string token)
        {
            var resultMode = new ResponseBaseModel<dynamic>
            {
                ResultCode = ResponceCodeEnum.Fail,
                Message = ""
            };

            var userData = RedisCacheHelper.Get<WeChatAccountModel>(RedisCacheKey.AuthTokenKey + token);
            var tempUserId = userData?.AccountId;
            if (tempUserId == null || tempUserId < 1)
            {
                resultMode.Message = "登录失效，请重新登录";
                return resultMode;
            }

            var userId = tempUserId.Value;

            try
            {
                var personService = new PersonService();
                var personTagService = new PersonTagService();

                // 获取无项目的人员列表
                var unassignedPersons = personService.GetUnassignedPersons(userId);
                var personList = new List<object>();

                foreach (var person in unassignedPersons)
                {
                    // 获取人员标签
                    var tags = personTagService.GetListByPersonId(person.Id, userId);
                    var tagList = tags.Select(t => new { id = t.Id, name = t.TagName }).ToList();

                    personList.Add(new
                    {
                        id = person.Id,
                        name = person.PersonName,
                        color = person.PersonColor,
                        tags = tagList
                    });
                }

                resultMode.Data = personList;
                resultMode.ResultCode = ResponceCodeEnum.Success;
            }
            catch (Exception ex)
            {
                resultMode.Message = "获取数据失败：" + ex.Message;
            }

            return resultMode;
        }

        /// <summary>
        /// 创建项目
        /// </summary>
        /// <param name="token">用户token</param>
        /// <param name="projectName">项目名称</param>
        /// <param name="startDate">开始日期</param>
        /// <returns></returns>
        [HttpGet]
        public ResponseBaseModel<dynamic> CreateProject(string token, string projectName, DateTime startDate)
        {
            var resultMode = new ResponseBaseModel<dynamic>
            {
                ResultCode = ResponceCodeEnum.Fail,
                Message = ""
            };

            if (string.IsNullOrEmpty(projectName))
            {
                resultMode.Message = "项目名称不能为空";
                return resultMode;
            }

            var userData = RedisCacheHelper.Get<WeChatAccountModel>(RedisCacheKey.AuthTokenKey + token);
            var tempUserId = userData?.AccountId;
            if (tempUserId == null || tempUserId < 1)
            {
                resultMode.Message = "登录失效，请重新登录";
                return resultMode;
            }

            var userId = tempUserId.Value;

            try
            {
                var projectService = new ProjectService();

                // 检查项目名称是否已存在
                if (projectService.IsProjectNameExists(projectName, userId))
                {
                    resultMode.Message = "项目名称已存在";
                    return resultMode;
                }

                var newProject = new ProjectModel
                {
                    ProjectName = projectName.Trim(),
                    StartDate = startDate,
                    UserId = userId,
                    CreateTime = DateTime.Now,
                    UpdateTime = DateTime.Now,
                    CreateUserId = userId,
                    UpdateUserId = userId,
                    IsDel = FlagEnum.HadZore,
                    IsValid = FlagEnum.HadOne,
                    Sort = 0
                };

                var projectId = projectService.Add(newProject);

                resultMode.Data = new
                {
                    id = projectId,
                    name = projectName,
                    startDate = startDate.ToString("yyyy-MM-dd"),
                    persons = new List<object>()
                };
                resultMode.ResultCode = ResponceCodeEnum.Success;
                resultMode.Message = "项目创建成功";
            }
            catch (Exception ex)
            {
                resultMode.Message = "创建项目失败：" + ex.Message;
            }

            return resultMode;
        }

        /// <summary>
        /// 更新项目
        /// </summary>
        /// <param name="token">用户token</param>
        /// <param name="id">项目ID</param>
        /// <param name="projectName">项目名称</param>
        /// <param name="startDate">开始日期</param>
        /// <returns></returns>
        [HttpGet]
        public ResponseBaseModel<dynamic> UpdateProject(string token, long id, string projectName, DateTime startDate)
        {
            var resultMode = new ResponseBaseModel<dynamic>
            {
                ResultCode = ResponceCodeEnum.Fail,
                Message = ""
            };

            if (string.IsNullOrEmpty(projectName))
            {
                resultMode.Message = "项目名称不能为空";
                return resultMode;
            }

            var userData = RedisCacheHelper.Get<WeChatAccountModel>(RedisCacheKey.AuthTokenKey + token);
            var tempUserId = userData?.AccountId;
            if (tempUserId == null || tempUserId < 1)
            {
                resultMode.Message = "登录失效，请重新登录";
                return resultMode;
            }

            var userId = tempUserId.Value;

            try
            {
                var projectService = new ProjectService();
                var project = projectService.Get(id);

                if (project == null)
                {
                    resultMode.Message = "项目不存在或无权限访问";
                    return resultMode;
                }

                // 检查项目名称是否已存在（排除当前项目）
                if (projectService.IsProjectNameExists(projectName, userId, id))
                {
                    resultMode.Message = "项目名称已存在";
                    return resultMode;
                }

                project.ProjectName = projectName.Trim();
                project.StartDate = startDate;
                project.UpdateTime = DateTime.Now;
                project.UpdateUserId = userId;

                projectService.Update(project);

                resultMode.Data = new
                {
                    id = project.Id,
                    name = project.ProjectName,
                    startDate = project.StartDate.ToString("yyyy-MM-dd")
                };
                resultMode.ResultCode = ResponceCodeEnum.Success;
                resultMode.Message = "项目更新成功";
            }
            catch (Exception ex)
            {
                resultMode.Message = "更新项目失败：" + ex.Message;
            }

            return resultMode;
        }

        /// <summary>
        /// 删除项目
        /// </summary>
        /// <param name="token">用户token</param>
        /// <param name="id">项目ID</param>
        /// <returns></returns>
        [HttpGet]
        public ResponseBaseModel<dynamic> DeleteProject(string token, long id)
        {
            var resultMode = new ResponseBaseModel<dynamic>
            {
                ResultCode = ResponceCodeEnum.Fail,
                Message = ""
            };

            var userData = RedisCacheHelper.Get<WeChatAccountModel>(RedisCacheKey.AuthTokenKey + token);
            var tempUserId = userData?.AccountId;
            if (tempUserId == null || tempUserId < 1)
            {
                resultMode.Message = "登录失效，请重新登录";
                return resultMode;
            }

            var userId = tempUserId.Value;

            try
            {
                var projectService = new ProjectService();
                var personService = new PersonService();
                var project = projectService.Get(id);

                if (project == null)
                {
                    resultMode.Message = "项目不存在或无权限访问";
                    return resultMode;
                }

                // 先清空该项目下所有人员的项目ID，让人员变成无项目状态
                personService.ClearProjectIdByProjectId(id, userId);

                // 再删除项目
                project.IsDel = FlagEnum.HadOne;
                project.UpdateTime = DateTime.Now;
                project.UpdateUserId = userId;

                projectService.Update(project);

                resultMode.ResultCode = ResponceCodeEnum.Success;
                resultMode.Message = "项目删除成功";
            }
            catch (Exception ex)
            {
                resultMode.Message = "删除项目失败：" + ex.Message;
            }

            return resultMode;
        }

        #endregion

        #region [2、人员管理]

        /// <summary>
        /// 创建人员
        /// </summary>
        /// <param name="token">用户token</param>
        /// <param name="personName">人员姓名</param>
        /// <param name="projectId">项目ID</param>
        /// <param name="personColor">人员颜色</param>
        /// <returns></returns>
        [HttpGet]
        public ResponseBaseModel<dynamic> CreatePerson(string token, string personName, long projectId, string personColor = "")
        {
            var resultMode = new ResponseBaseModel<dynamic>
            {
                ResultCode = ResponceCodeEnum.Fail,
                Message = ""
            };

            if (string.IsNullOrEmpty(personName))
            {
                resultMode.Message = "人员姓名不能为空";
                return resultMode;
            }

            var userData = RedisCacheHelper.Get<WeChatAccountModel>(RedisCacheKey.AuthTokenKey + token);
            var tempUserId = userData?.AccountId;
            if (tempUserId == null || tempUserId < 1)
            {
                resultMode.Message = "登录失效，请重新登录";
                return resultMode;
            }

            var userId = tempUserId.Value;

            try
            {
                var projectService = new ProjectService();
                var personService = new PersonService();

                // 验证项目是否存在且属于当前用户
                var project = projectService.Get(projectId);
                if (project == null && projectId!=0)
                {
                    resultMode.Message = "项目不存在或无权限访问";
                    return resultMode;
                }

                // 检查人员姓名是否在当前项目中已存在
                if (personService.IsPersonNameExistsInProject(personName, userId, projectId))
                {
                    resultMode.Message = $"人员\"{personName}\"在当前项目中已存在";
                    return resultMode;
                }

                // 检查人员姓名是否存在
                var existingPerson = personService.GetByName(personName, userId);
                if (existingPerson != null)
                {
                    var personTagService = new PersonTagService();

                    // 如果人员在其他项目中（ProjectId > 0）
                    if (existingPerson.ProjectId > 0 && projectId != 0)
                    {
                        var existingProject = projectService.Get(existingPerson.ProjectId);

                        // 获取人员标签
                        var tags = personTagService.GetListByPersonId(existingPerson.Id, userId);
                        var tagList = tags.Select(t => new { id = t.Id, name = t.TagName }).ToList();

                        resultMode.Message = $"人员\"{personName}\"已存在于\"{existingProject.ProjectName}\"项目中";
                        resultMode.Data = new
                        {
                            existingPerson = new
                            {
                                id = existingPerson.Id,
                                name = existingPerson.PersonName,
                                color = existingPerson.PersonColor,
                                projectName = existingProject.ProjectName,
                                tags = tagList
                            }
                        };
                        return resultMode;
                    }
                    else
                    {
                        // 人员存在但无项目（ProjectId = 0），直接分配到新项目
                        existingPerson.ProjectId = projectId;
                        existingPerson.UpdateTime = DateTime.Now;
                        existingPerson.UpdateUserId = userId;

                        // 如果没有颜色，设置默认颜色
                        if (string.IsNullOrEmpty(existingPerson.PersonColor))
                        {
                            if (string.IsNullOrEmpty(personColor))
                            {
                                var colors = new[]
                                {
                                    "linear-gradient(135deg, #667eea 0%, #764ba2 100%)",
                                    "linear-gradient(135deg, #f093fb 0%, #f5576c 100%)",
                                    "linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)",
                                    "linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)",
                                    "linear-gradient(135deg, #fa709a 0%, #fee140 100%)"
                                };
                                var random = new Random();
                                personColor = colors[random.Next(colors.Length)];
                            }
                            existingPerson.PersonColor = personColor;
                        }

                        personService.Update(existingPerson);

                        // 获取人员标签
                        var tags = personTagService.GetListByPersonId(existingPerson.Id, userId);
                        var tagList = tags.Select(t => new { id = t.Id, name = t.TagName }).ToList();

                        resultMode.Data = new
                        {
                            id = existingPerson.Id,
                            name = existingPerson.PersonName,
                            color = existingPerson.PersonColor,
                            tags = tagList
                        };
                        resultMode.ResultCode = ResponceCodeEnum.Success;
                        resultMode.Message = $"人员\"{personName}\"已加入项目";
                        return resultMode;
                    }
                }

                // 设置默认颜色
                if (string.IsNullOrEmpty(personColor))
                {
                    var colors = new[]
                    {
                        "linear-gradient(135deg, #667eea 0%, #764ba2 100%)",
                        "linear-gradient(135deg, #f093fb 0%, #f5576c 100%)",
                        "linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)",
                        "linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)",
                        "linear-gradient(135deg, #fa709a 0%, #fee140 100%)"
                    };
                    var random = new Random();
                    personColor = colors[random.Next(colors.Length)];
                }

                var newPerson = new PersonModel
                {
                    PersonName = personName.Trim(),
                    ProjectId = projectId,
                    PersonColor = personColor,
                    UserId = userId,
                    CreateTime = DateTime.Now,
                    UpdateTime = DateTime.Now,
                    CreateUserId = userId,
                    UpdateUserId = userId,
                    IsDel = FlagEnum.HadZore,
                    IsValid = FlagEnum.HadOne,
                    Sort = 0
                };

                var personId = personService.Add(newPerson);

                resultMode.Data = new
                {
                    id = personId,
                    name = personName,
                    color = personColor,
                    tags = new List<string>()
                };
                resultMode.ResultCode = ResponceCodeEnum.Success;
                resultMode.Message = "人员创建成功";
            }
            catch (Exception ex)
            {
                resultMode.Message = "创建人员失败：" + ex.Message;
            }

            return resultMode;
        }

        /// <summary>
        /// 移动人员到其他项目
        /// </summary>
        /// <param name="token">用户token</param>
        /// <param name="personId">人员ID</param>
        /// <param name="targetProjectId">目标项目ID</param>
        /// <returns></returns>
        [HttpGet]
        public ResponseBaseModel<dynamic> MovePerson(string token, long personId, long targetProjectId)
        {
            var resultMode = new ResponseBaseModel<dynamic>
            {
                ResultCode = ResponceCodeEnum.Fail,
                Message = ""
            };

            var userData = RedisCacheHelper.Get<WeChatAccountModel>(RedisCacheKey.AuthTokenKey + token);
            var tempUserId = userData?.AccountId;
            if (tempUserId == null || tempUserId < 1)
            {
                resultMode.Message = "登录失效，请重新登录";
                return resultMode;
            }

            var userId = tempUserId.Value;

            try
            {
                var projectService = new ProjectService();
                var personService = new PersonService();

                // 验证人员是否存在且属于当前用户
                var person = personService.Get(personId);
                if (person == null)
                {
                    resultMode.Message = "人员不存在或无权限访问";
                    return resultMode;
                }

                // 验证目标项目是否存在且属于当前用户
                var targetProject = projectService.Get(targetProjectId);
                if (targetProject == null && targetProjectId!=0)
                {
                    resultMode.Message = "目标项目不存在或无权限访问";
                    return resultMode;
                }

                // 如果已经在目标项目中，则不需要移动
                if (person.ProjectId == targetProjectId)
                {
                    resultMode.Message = "人员已在目标项目中";
                    return resultMode;
                }

                // 更新人员的项目ID
                person.ProjectId = targetProjectId;
                person.UpdateTime = DateTime.Now;
                person.UpdateUserId = userId;

                personService.Update(person);

                resultMode.ResultCode = ResponceCodeEnum.Success;
                resultMode.Message = $"{person.PersonName}已移动到{targetProject.ProjectName}";
            }
            catch (Exception ex)
            {
                resultMode.Message = "移动人员失败：" + ex.Message;
            }

            return resultMode;
        }

        #endregion

        #region [3、标签管理]

        /// <summary>
        /// 添加人员标签
        /// </summary>
        /// <param name="token">用户token</param>
        /// <param name="personId">人员ID</param>
        /// <param name="tagName">标签名称</param>
        /// <returns></returns>
        [HttpGet]
        public ResponseBaseModel<dynamic> AddPersonTag(string token, long personId, string tagName)
        {
            var resultMode = new ResponseBaseModel<dynamic>
            {
                ResultCode = ResponceCodeEnum.Fail,
                Message = ""
            };

            if (string.IsNullOrEmpty(tagName))
            {
                resultMode.Message = "标签名称不能为空";
                return resultMode;
            }

            var userData = RedisCacheHelper.Get<WeChatAccountModel>(RedisCacheKey.AuthTokenKey + token);
            var tempUserId = userData?.AccountId;
            if (tempUserId == null || tempUserId < 1)
            {
                resultMode.Message = "登录失效，请重新登录";
                return resultMode;
            }

            var userId = tempUserId.Value;

            try
            {
                var personService = new PersonService();
                var personTagService = new PersonTagService();

                // 验证人员是否存在且属于当前用户
                var person = personService.Get(personId);
                if (person == null || person.UserId != userId)
                {
                    resultMode.Message = "人员不存在或无权限访问";
                    return resultMode;
                }

                // 检查标签是否已存在
                if (personTagService.IsTagExists(personId, tagName, userId))
                {
                    resultMode.Message = "标签已存在";
                    return resultMode;
                }

                var newTag = new PersonTagModel
                {
                    PersonId = personId,
                    TagName = tagName.Trim(),
                    UserId = userId,
                    CreateTime = DateTime.Now,
                    UpdateTime = DateTime.Now,
                    CreateUserId = userId,
                    UpdateUserId = userId,
                    IsDel = FlagEnum.HadZore,
                    IsValid = FlagEnum.HadOne,
                    Sort = 0
                };

                var tagId = personTagService.Add(newTag);

                resultMode.Data = new
                {
                    id = tagId,
                    tagName = tagName
                };
                resultMode.ResultCode = ResponceCodeEnum.Success;
                resultMode.Message = "标签添加成功";
            }
            catch (Exception ex)
            {
                resultMode.Message = "添加标签失败：" + ex.Message;
            }

            return resultMode;
        }

        /// <summary>
        /// 删除人员标签
        /// </summary>
        /// <param name="token">用户token</param>
        /// <param name="tagId">标签ID</param>
        /// <returns></returns>
        [HttpGet]
        public ResponseBaseModel<dynamic> DeletePersonTag(string token, long tagId)
        {
            var resultMode = new ResponseBaseModel<dynamic>
            {
                ResultCode = ResponceCodeEnum.Fail,
                Message = ""
            };

            var userData = RedisCacheHelper.Get<WeChatAccountModel>(RedisCacheKey.AuthTokenKey + token);
            var tempUserId = userData?.AccountId;
            if (tempUserId == null || tempUserId < 1)
            {
                resultMode.Message = "登录失效，请重新登录";
                return resultMode;
            }

            var userId = tempUserId.Value;

            try
            {
                var personTagService = new PersonTagService();
                var tag = personTagService.Get(tagId);

                if (tag == null || tag.UserId != userId)
                {
                    resultMode.Message = "标签不存在或无权限访问";
                    return resultMode;
                }

                tag.IsDel = FlagEnum.HadOne;
                tag.UpdateTime = DateTime.Now;
                tag.UpdateUserId = userId;

                personTagService.Update(tag);

                resultMode.ResultCode = ResponceCodeEnum.Success;
                resultMode.Message = "标签删除成功";
            }
            catch (Exception ex)
            {
                resultMode.Message = "删除标签失败：" + ex.Message;
            }

            return resultMode;
        }

        #endregion

        #region [4、人员管理API]

        /// <summary>
        /// 获取所有人员信息
        /// </summary>
        /// <param name="token">用户token</param>
        /// <param name="tagIds">标签ID列表（可选，多个用逗号分隔）</param>
        /// <returns></returns>
        [HttpGet]
        public ResponseBaseModel<dynamic> GetAllPersons(string token, string tagIds = "")
        {
            var resultMode = new ResponseBaseModel<dynamic>
            {
                ResultCode = ResponceCodeEnum.Fail,
                Message = ""
            };

            var userData = RedisCacheHelper.Get<WeChatAccountModel>(RedisCacheKey.AuthTokenKey + token);
            var tempUserId = userData?.AccountId;
            if (tempUserId == null || tempUserId < 1)
            {
                resultMode.Message = "登录失效，请重新登录";
                resultMode.ResultCode = ResponceCodeEnum.NeedLogin;
                return resultMode;
            }

            var userId = tempUserId.Value;

            try
            {
                var personService = new PersonService();
                var personTagService = new PersonTagService();
                var projectService = new ProjectService();

                // 解析标签ID列表
                List<long> tagIdList = null;
                if (!string.IsNullOrEmpty(tagIds))
                {
                    var tagIdStrings = tagIds.Split(new[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries);
                    tagIdList = new List<long>();
                    long tagId;
                    foreach (var tagIdStr in tagIdStrings)
                    {
                        if (long.TryParse(tagIdStr.Trim(), out tagId) && tagId > 0)
                        {
                            tagIdList.Add(tagId);
                        }
                    }
                    if (tagIdList.Count == 0)
                    {
                        tagIdList = null;
                    }
                }

                // 获取所有人员列表
                var allPersons = personService.GetAllPersons(userId, tagIdList);
                var personList = new List<object>();

                foreach (var person in allPersons)
                {
                    // 获取人员标签
                    var tags = personTagService.GetListByPersonId(person.Id, userId);
                    var tagList = tags.Select(t => new { id = t.Id, name = t.TagName }).ToList();

                    // 获取项目信息
                    string projectName = "无项目";
                    if (person.ProjectId > 0)
                    {
                        var project = projectService.Get(person.ProjectId);
                        if (project != null)
                        {
                            projectName = project.ProjectName;
                        }
                    }

                    personList.Add(new
                    {
                        id = person.Id,
                        name = person.PersonName,
                        color = person.PersonColor,
                        projectId = person.ProjectId,
                        projectName = projectName,
                        tags = tagList,
                        createTime = person.CreateTime.ToString("yyyy-MM-dd HH:mm:ss")
                    });
                }

                resultMode.Data = personList;
                resultMode.ResultCode = ResponceCodeEnum.Success;
                resultMode.Message = "获取成功";
            }
            catch (Exception ex)
            {
                resultMode.Message = "获取数据失败：" + ex.Message;
            }

            return resultMode;
        }

        /// <summary>
        /// 删除指定人员
        /// </summary>
        /// <param name="token">用户token</param>
        /// <param name="personId">人员ID</param>
        /// <returns></returns>
        [HttpGet]
        public ResponseBaseModel<dynamic> DeletePerson(string token, long personId)
        {
            var resultMode = new ResponseBaseModel<dynamic>
            {
                ResultCode = ResponceCodeEnum.Fail,
                Message = ""
            };

            if (personId <= 0)
            {
                resultMode.Message = "人员ID无效";
                return resultMode;
            }

            var userData = RedisCacheHelper.Get<WeChatAccountModel>(RedisCacheKey.AuthTokenKey + token);
            var tempUserId = userData?.AccountId;
            if (tempUserId == null || tempUserId < 1)
            {
                resultMode.Message = "登录失效，请重新登录";
                resultMode.ResultCode = ResponceCodeEnum.NeedLogin;
                return resultMode;
            }

            var userId = tempUserId.Value;

            try
            {
                var personService = new PersonService();
                var personTagService = new PersonTagService();

                // 验证人员是否存在且属于当前用户
                var person = personService.Get(personId);
                if (person == null)
                {
                    resultMode.Message = "人员不存在或无权限访问";
                    return resultMode;
                }

                // 先删除该人员的所有标签
                var tags = personTagService.GetListByPersonId(personId, userId);
                foreach (var tag in tags)
                {
                    tag.IsDel = FlagEnum.HadOne;
                    tag.UpdateTime = DateTime.Now;
                    tag.UpdateUserId = userId;
                    personTagService.Update(tag);
                }

                // 删除人员
                personService.DelModel(personId);

                resultMode.ResultCode = ResponceCodeEnum.Success;
                resultMode.Message = "人员删除成功";
            }
            catch (Exception ex)
            {
                resultMode.Message = "删除人员失败：" + ex.Message;
            }

            return resultMode;
        }

        #endregion
    }
}